package com.vdong.common.oauth.common.authorize;

import com.alibaba.dubbo.config.annotation.Reference;
import com.vdong.kpay.basics.dubbo.api.auth.AuthBusinessRoleAndPermissionService;
import com.vdong.kpay.basics.dubbo.api.auth.AuthUserService;
import com.vdong.kpay.basics.dubbo.api.platform.SaasUserService;
import com.vdong.kpay.basics.dubbo.pojo.auth.BusinessRole;
import com.vdong.kpay.basics.dubbo.pojo.backend.UserMain;
import com.vdong.kpay.basics.dubbo.pojo.platform.SaasUser;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.Date;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

/**
 * @author 刀锋
 * @date : Create in 8:43 2018/6/14
 * @description:
 */
@Component
public class AuthUserDetailService {
    @Reference(version = "1.0.0")
    private AuthUserService userService;

    @Reference(version = "1.0.0")
    private SaasUserService saasUserService;

    @Reference(version = "1.0.0")
    private AuthBusinessRoleAndPermissionService businessRoleAndPermissionService;

    protected final Log logger = LogFactory.getLog(getClass());

    public UserDetails loadUserByUsernameAndType(String username, AuthWebAuthenticationDetails details) throws UsernameNotFoundException {
        Integer userType = details.getUserType();

        if (null == userType) {
            throw new UsernameNotFoundException("用户类型不能为空");
        }
        switch (userType) {
            case AuthCommon.User.SAAS_USER:
                return getSAASUser(username, details);
            case AuthCommon.User.STORE_USER:
                Long storeId = details.getStoreId();
                //UserDetails storeUser = getStoreUser(username, storeId, details);
                return getStoreUser(username, storeId, details);

            default:
                throw new UsernameNotFoundException("未知的用户类型");
        }
    }

    private UserDetails getSAASUser(String username, AuthWebAuthenticationDetails details) throws UsernameNotFoundException {
        logger.info("getAccountStatus----------------3243242342342342343242342342342423424---->");
        logger.debug("getAccountStatus----------------3243242342342342343242342342342423424---->");
        SaasUser userByName = saasUserService.findUserByName(username);
        if (null == userByName) {
            throw new UsernameNotFoundException(username + "账号不存在或已禁用");
        }

        details.setUserId(userByName.getId());
        UserDetails user = User.withUsername(username)
                .password(userByName.getPassword())
                .authorities("ROLE_SAAS_ADMIN")
                .build();
        return user;
    }

    private UserDetails getStoreUser(String username, Long storeId, AuthWebAuthenticationDetails details) throws UsernameNotFoundException {
        logger.info("getAccountStatus----------------3243242342342342343242342342342423424---->");
        logger.debug("getAccountStatus----------------3243242342342342343242342342342423424---->");
        //username 唯一
        UserMain userMain = null;
        if (storeId != null) {
            userMain = userService.findUserByUsernameAndStoreId(username, storeId);

        } else {
            //details.getDomain();//todo 通过域名方式识别店铺id 找到用户
        }
        if (null == userMain) {
            throw new UsernameNotFoundException(username + "账号不存在 or 已禁用");
        }
        if (userMain.getEndDate() != null && new Date().after(userMain.getEndDate())) {
            throw new UsernameNotFoundException(username + "账号已经到期");
        }

        if (userMain.getAccountStatus() != null && 1 != userMain.getAccountStatus()) {
            throw new UsernameNotFoundException(username + "账号已关闭");
        }
        details.setUserId(userMain.getId());
        List<BusinessRole> roles = businessRoleAndPermissionService.userRoles(userMain);
        return User.withUsername(username)
                .password(userMain.getPassword())
                .authorities(convertUserRoles(roles).toArray(new String[roles.size()]))
                .build();
    }

    /**
     * 将业务角色对象转换成spring security 鉴权用的对象
     *
     * @param roles
     * @return
     */
    private Set<String> convertUserRoles(List<BusinessRole> roles) {
        Set<String> roleSet = new HashSet<>();
        if (!CollectionUtils.isEmpty(roles)) {
            for (int i = 0; i < roles.size(); i++) {
                BusinessRole role = roles.get(i);
                String roleName = role.getEnname();
                if (!StringUtils.isEmpty(roleName)) {
                    roleSet.add(roleName);
                }
            }
        }
        return roleSet;
    }
}
